import type { ApiResult, PageQuery, PageResult } from '#/utils/daprplus';

import { requestClient } from '#/api/request';

export enum ResourceType {
  Api = 2,
  Entity = 1,
  File = 5,
  Function = 3,
  UI = 4,
}

export enum ResourceAccessType {
  Anonymous = 1,
  LoggedIn = 2,
  None = 0,
  RoleLimit = 3,
}

export interface ResourceOperation {
  code: string;
  display: string;
  accessType: ResourceAccessType;
  isAccessTypeChanged: boolean;
  color?: string;
}

export type ServiceName = 'IdentityApi';

export interface ResourceOutDto {
  id: string;
  name: string;
  code: string;
  description?: string;
  serviceName: string;
  type: ResourceType;
  accessType: ResourceAccessType;
  isSystem: boolean;
  isLocked: boolean;
  metadata?: Record<string, unknown>;
  allowedOperations?: ResourceOperation[];
}

export interface ResourceInDto {
  id: string;
  name: string;
  code: string;
  description?: string;
  serviceName: string;
  type: ResourceType;
  accessType: ResourceAccessType;
  isLocked: boolean;
  metadata?: Record<string, unknown>;
  allowedOperations?: ResourceOperation[];
}

export interface ResourceOperation {
  code: string;
  display: string;
  accessType: ResourceAccessType;
  isAccessTypeChanged: boolean;
  color?: string;
}

export interface EntityProperty {
  name: string;
  display: string;
  typeName: string;
  valueRange: unknown[];
}

export interface EntityMetadata {
  typeName: string;
  auditEnabled: boolean;
  properties: EntityProperty[];
}

export async function getResourcePageApi(query: PageQuery, service: string) {
  const result = await requestClient.post<PageResult>(
    '/api/resource/read',
    { service, query },
    {
      responseReturn: 'data',
    },
  );
  return { items: result.data, total: result.total };
}

export async function createResourcesApi(
  dtos: ResourceInDto[],
  service: string,
) {
  doEnum(dtos);
  const result = await requestClient.post<ApiResult>(`/api/resource`, {
    service,
    dtos,
  });
  return result;
}

export async function updateResourcesApi(
  dtos: ResourceInDto[],
  service: string,
) {
  doEnum(dtos);
  const result = await requestClient.put<ApiResult>(`/api/resource`, {
    service,
    dtos,
  });
  return result;
}

export async function deleteResourcesApi(ids: string[], service: string) {
  const result = await requestClient.delete<ApiResult>(`/api/resource`, {
    service,
    ids,
  });
  return result;
}

function doEnum(dtos: ResourceInDto[]) {
  dtos.forEach((dto) => {
    dto.type = Number(dto.type) as ResourceType;
    dto.accessType = Number(dto.accessType) as ResourceAccessType;
  });
}
